package com.example.bigevent.controller;

import com.example.bigevent.common.constant.JwtClaimsConstant;
import com.example.bigevent.common.result.Result;
import com.example.bigevent.common.utils.JWTUtil;
import com.example.bigevent.pojo.entity.User;
import com.example.bigevent.properties.JWTProperties;
import com.example.bigevent.service.UserService;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {




    @Autowired
    public UserController(UserService userService, JWTProperties jwtProperties){
        this.userService=userService;
        this.jwtProperties=jwtProperties;
    }

    private final UserService userService;

    private final JWTProperties jwtProperties;


    /**
     * 用户注册
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回Result信息
     */

    @PostMapping("/register")
    public Result<String>register(@RequestParam @Pattern(regexp = "^\\${5,16}") String username,@RequestParam @Pattern(regexp = "^\\${5,16}") String password){
        log.info("注册：{}",username);
        if(userService.findByUsername(username)!=null){
            return Result.error("用户名被占用");
        }
        userService.register(username,password);
        return Result.success();
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回token给前端
     */
    @PostMapping("/login")
    public Result<String> login(@RequestParam String username,@RequestParam String password){
        log.info("登录:{}",username);
        User u=userService.findByUsername(username);
        if(u==null){
            return Result.error("用户不存在");
        }
        userService.login(username,password);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, u.getId());
        String token= JWTUtil.createJJWT(
                jwtProperties.getSecretKet()
                ,jwtProperties.getTtl()
                ,claims);
        return Result.success(token);
    }
}
